package com.jsmtr.rms.controller;

import java.util.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jsmtr.rms.entity.*;
import com.jsmtr.rms.utils.DateTools;
import com.jsmtr.rms.utils.StringTools;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.jsmtr.rms.service.IDoZZService;
import com.jsmtr.rms.service.IProjectService;
import com.jsmtr.rms.service.IRecommendService;
import com.jsmtr.rms.service.ISchoolService;
import com.jsmtr.rms.service.IUtilService;
import com.jsmtr.rms.utils.EnumTools;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller
@RequestMapping("/Do/ZZRecommend")
public class DoZZRecommendController {

    @Resource
    private IUtilService utilService;

    @Resource
    private IProjectService projectService;

    @Resource
    private ISchoolService schoolService;

    @Resource
    private IRecommendService recommendService;

    @Resource
    private IDoZZService doZZService;

    //[start] 查询毕业生信息

    //首页
    @RequestMapping("/")
    public String Index(HttpServletRequest request, Model model) {
        try {
            model.addAttribute("path", request.getContextPath());
            model.addAttribute("pid", request.getParameter("pid").trim());
            String fid = request.getParameter("fid").trim();
            model.addAttribute("fid", fid);
            model.addAttribute("deptcode", request.getParameter("deptcode").trim());

            StringBuilder str = new StringBuilder();
            List<HRSchoolUsers> schools = schoolService.getSchools();
            for (HRSchoolUsers school : schools) {
                str.append("<option value='" + school.getId() + "'>" + school.getUname() + "</option>");
            }
            model.addAttribute("school", str);
            /*String[] jobs=new String[]{"司机组","客服组","车辆组","通号组","供电组","车站设备组","工务组"};
            StringBuilder strjob = new StringBuilder();
            for (int i = 0; i <jobs.length ; i++) {
                strjob.append("<option value='" + jobs[i] + "'>" + jobs[i] + "</option>");
            }
            model.addAttribute("jobs", strjob);*/
            //招聘岗位
            List<ProjectInfoJobs> projectJobs=utilService.getProjectJobs(request.getParameter("pid").trim());
            model.addAttribute("jobs",projectJobs);
            ProjectInfoFlow projectInfoFlow= projectService.getFolwById(fid);
            if(projectInfoFlow!=null){
                model.addAttribute("nowflow",projectInfoFlow.getNickname());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "Do/ZZCampus/Recommend/index";
    }

    @SuppressWarnings("unchecked")
    @RequestMapping("/getusers")
    public void getusers(HttpServletRequest request, HttpServletResponse response, HRZZUser user) {
        try {
            int perpage = Integer.parseInt(request.getParameter("perpage"));
            int page = Integer.parseInt(request.getParameter("page"));
            String flowid = request.getParameter("flowid").trim();
            Map<String, Object> _map = new HashMap<String, Object>();
            _map.put("agefrom", request.getParameter("agefrom").length()<0?"":request.getParameter("agefrom").trim());
            _map.put("ageto", request.getParameter("ageto").length()<0?"":request.getParameter("ageto").trim());
            _map.put("heightfrom", request.getParameter("heightfrom").length()<0?"":request.getParameter("heightfrom").trim());
            _map.put("heightto", request.getParameter("heightto").length()<0?"":request.getParameter("heightto").trim());
            _map.put("graduationyear",request.getParameter("graduationyear").length()<0?"":request.getParameter("graduationyear").trim());
            _map.put("ischangejob",request.getParameter("ischangejob"));
            Map<String, Object> map = recommendService.getUserMap(page, perpage, user,_map);
            StringBuilder result = new StringBuilder();
            double pageCount = (Double) map.get("pageCount");
            double allcount = (Double) map.get("count");

            if (pageCount != 0) {
                List<HashMap> object = (List<HashMap>)map.get("list");
                int num = 1;
                for (HashMap<String,Object> _user :  object) {
                   /* result.append("<tr><td><input type=\"checkbox\" name='uid' value='" + _user.getId() + "' id='cb_" + _user.getId() + "' /></td>");
                    result.append("<td>" + (perpage * (page - 1) + num) + "</td>");
                    result.append("<td>" + _user.getName() + "</td>");
                    result.append("<td>" + _user.getGender() + "</td>");
                    result.append("<td>" + _user.getCode() + "</td>");
                    result.append("<td>" + _user.getMajor() + "</td>");
                    result.append("<td>" + _user.getGraduationtime() + "</td>");
                    result.append("<td>" + _user.getBx() + "</td>");
                    result.append("<td>" + _user.getGuake() + "</td>");
                    result.append("<td>" + _user.getTc() + "</td>");
                    result.append("<td>" + (_user.getDeptname() == null ? "未分配" : _user.getDeptname()) + "</td>");
                    result.append("<td>" + EnumTools.zzuserState.values()[_user.getState()] + "</td>");

                    if (_user.getFqstate().equals("已放弃")
                            && _user.getFqfid().equals(flowid)) {
                        result.append("<td class='yfq'><span>已放弃</span></td></tr>");
                    } else {
                        boolean bl = _user.getFid().equals(flowid);
                        result.append("<td class='" + bl + "'><span>" + (bl == true ? "未完成" : "已完成") + "</span></td></tr>");
                    }*/
                   //
                    //p.id,p.name,p.gender,p.code,p.job,p.graduationtime,p.bx,p.guake,u.height,p.major,p.state,p.csremarks,p.rstate,p.rmarks,u.userid,u.id drid,p.fid,p.fqstate,p.fqfid
                    result.append("<tr><td><input type=\"checkbox\" name='uid' value='" + _user.get("ID") + "' id='cb_" + _user.get("ID") + "' /></td>");
                    result.append("<td>" + (perpage * (page - 1) + num) + "</td>");
                    result.append("<td class='link'><a target='_blank' href='" + request.getContextPath() + "/UserResume/ViewDResume?id=" + _user.get("DRID") + "'>" + _user.get("NAME") + "</a></td>");
                    result.append("<td>" + _user.get("GENDER") + "</td>");
                    result.append("<td>" + _user.get("CODE") + "</td>");
                    result.append("<td>" + _user.get("MAJOR") + "</td>");
                    result.append("<td>" + _user.get("GRADUATIONTIME") + "</td>");
                    result.append("<td>" + _user.get("BX") + "</td>");
                    result.append("<td>" + _user.get("GUAKE") + "</td>");
                    result.append("<td>" + _user.get("HEIGHT") + "</td>");
                    result.append("<td>" + _user.get("JOB")+ "</td>");
                    if(_user.get("STATE").toString().equalsIgnoreCase("2")){
                        result.append("<td>已通过</td>");
                    }else{
                        result.append("<td title="+_user.get("CSREMARKS")+" style=\"color:red\">未通过</td>");
                    }

                    if(_user.get("RSTATE").toString().equalsIgnoreCase("未通过")){
                        result.append("<td  style=\"color:red\">" +_user.get("RSTATE") + "</td>");
                    }else{
                        result.append("<td>" +_user.get("RSTATE") + "</td>");

                    }

                    result.append("<td>" + (_user.get("RMARKS")==null?"":_user.get("RMARKS")) + "</td>");


                    result.append("<td>");
                    if ( _user.get("FQSTATE").toString().equals("已放弃")
                            && _user.get("FQFID").equals(flowid)) {

                        // result.append("<td class='yfq'><span>已放弃</span></td></tr>");
                        result.append("<span class='layui-badge layui-bg-gray' title='已放弃'>弃</span>");
                    } else {
                        if (_user.get("STATE").equals("未处理")) {
                            // result.append("<td class='true'><span>未完成</span></td></tr>");
                            result.append("<span class='layui-badge layui-bg-orange' title='未完成'>未</span>");
                        } else if (_user.get("STATE").equals("未通过")||_user.get("STATE").equals("不通过")||_user.get("STATE").equals("不合格")||_user.get("STATE").equals("未合格")) {
                            result.append("<span class='layui-badge layui-bg-green' title='已完成'>完</span>");
                            //result.append("<td class='false'><span>已完成</span></td></tr>");
                        } else {
                            boolean bl = _user.get("FID").equals(flowid);
                            if (bl){
                                result.append("<span class='layui-badge layui-bg-orange' title='未完成'>未</span>");
                            }else{
                                result.append("<span class='layui-badge layui-bg-green' title='已完成'>完</span>");
                            }
                            // result.append("<td class='" + bl + "'><span>" + (bl == true ? "未完成" : "已完成") + "</span></td></tr>");

                        }
                    }
                    if (StringTools.trimNotEmpty(_user.get("NRID"))){
                        result.append("<span class='layui-badge layui-bg-blue' title='转岗(原岗位:"+_user.get("NJNAME")+")'>岗</span>");
                    }
                    result.append("</td>");
                    result.append("</tr>");

                    num++;
                }
            } else {
                result.append("<tr style='display:none'><td></td></tr>");
            }
            result.append("<input type='hidden' id='pageCount' value='" + pageCount + "' />");
            result.append("<input type='hidden' id='allCount' value='" + allcount + "' />");
            utilService.printTextResult(result.toString(), response);
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printTextResult("<tr><td colspan='15'>读取数据失败</td></tr><input type='hidden' id='pageCount' value='0' /><input type='hidden' id='allCount' value='0' />", response);
        }

    }
    //[end]

    @ResponseBody
    @RequestMapping(value = "/getZZRecommendListLayuiJson", method = RequestMethod.GET)
    public LayuiDataTableResultBean getZZRecommendListLayuiJson(HttpServletRequest request, HttpServletResponse response, HRZZUser user) {
        try {
            int page = Integer.parseInt(request.getParameter("page"));
            int limit = Integer.parseInt(request.getParameter("limit"));
            String flowid = request.getParameter("flowid").trim();
            Map<String, Object> _map = new HashMap<String, Object>();
            _map.put("agefrom", request.getParameter("agefrom").length()<0?"":request.getParameter("agefrom").trim());
            _map.put("ageto", request.getParameter("ageto").length()<0?"":request.getParameter("ageto").trim());
            _map.put("heightfrom", request.getParameter("heightfrom").length()<0?"":request.getParameter("heightfrom").trim());
            _map.put("heightto", request.getParameter("heightto").length()<0?"":request.getParameter("heightto").trim());
            _map.put("graduationyear",request.getParameter("graduationyear").length()<0?"":request.getParameter("graduationyear").trim());
            _map.put("ischangejob",request.getParameter("ischangejob"));
            Map<String, Object> map = recommendService.getUserMap(page, limit, user,_map);

            double pageCount = (Double) map.get("pageCount");
            double allcount = (Double) map.get("count");

            JSONArray jsonArray = new JSONArray();
            int num = 1;
            if (pageCount != 0) {
                List<HashMap> object = (List<HashMap>)map.get("list");
                for (HashMap<String,Object> _user :  object) {
                    JSONObject jsonObject = new JSONObject();

                    jsonObject.put("id_cb","cb_" + _user.get("ID"));
                    jsonObject.put("id",limit * (page - 1) + num);
                    jsonObject.put("cardcount", (_user.get("CARDCOUNT")== null ? "" : Integer.parseInt(_user.get("CARDCOUNT").toString()))); //投简历总次数
                    jsonObject.put("ContextPath",request.getContextPath()+"/UserResume/ViewDResume?id=" + _user.get("DRID"));
                    jsonObject.put("NAME", _user.get("NAME"));
                    jsonObject.put("CARDNO", _user.get("CODE"));
                    jsonObject.put("SEXNAME", _user.get("GENDER"));
                    jsonObject.put("MAJORNAME", _user.get("MAJOR"));
                    jsonObject.put("GRADUATIONTIME", (_user.get("GRADUATIONTIME")== null ? "" : _user.get("GRADUATIONTIME")));
                    jsonObject.put("BX", _user.get("BX"));
                    jsonObject.put("GUAKE", _user.get("GUAKE"));
                    jsonObject.put("HEIGHT", _user.get("HEIGHT"));
                    jsonObject.put("JOB", _user.get("JOB"));
                    jsonObject.put("STATE", _user.get("STATE"));
                    jsonObject.put("CSREMARKS", _user.get("CSREMARKS"));
                    jsonObject.put("RSTATE", _user.get("RSTATE"));

                    if(_user.get("STATE").toString().equalsIgnoreCase("2")){
                        jsonObject.put("STATEa", "已通过");
                    }else{
                        jsonObject.put("STATEa", "未通过");
                    }

                    jsonObject.put("STATEb", _user.get("RSTATE"));
                    jsonObject.put("RMARKS", (_user.get("RMARKS")== null ? "" : _user.get("RMARKS")));

                    jsonObject.put("FQSTATE", _user.get("FQSTATE"));
                    jsonObject.put("FQFID", _user.get("FQFID"));
                    jsonObject.put("NJNAME", _user.get("NJNAME"));
                    jsonObject.put("FID", _user.get("FID"));
                    if ( _user.get("FQSTATE").toString().equals("已放弃") && _user.get("FQFID").equals(flowid)) {
                        jsonObject.put("STATEc", "弃");
                    } else {
                        if (_user.get("STATE").equals("未处理")) {
                            jsonObject.put("STATEc", "未");
                        } else if (_user.get("STATE").equals("未通过")||_user.get("STATE").equals("不通过")||_user.get("STATE").equals("不合格")||_user.get("STATE").equals("未合格")) {
                            jsonObject.put("STATEc", "完");
                        } else {
                            boolean bl = _user.get("FID").equals(flowid);
                            if (bl){
                                jsonObject.put("STATEc", "未");
                            }else{
                                jsonObject.put("STATEc", "完");
                            }
                        }
                    }

                    if (StringTools.trimNotEmpty(_user.get("NRID"))){
                        jsonObject.put("NJNAME", _user.get("NJNAME"));
                        jsonObject.put("STATEd", _user.get("岗"));
                    }else
                        jsonObject.put("NRID", "");

                    jsonArray.add(jsonObject);
                    num++;
                }
            }

            LayuiDataTableResultBean result = new LayuiDataTableResultBean();
            result.setCode(0);
            result.setMsg("success");
            result.setCount((int) allcount);
            result.setData(jsonArray);

            return result;
        } catch (Exception e) {
            e.printStackTrace();

            LayuiDataTableResultBean result = new LayuiDataTableResultBean();
            result.setCount(-1);
            result.setMsg("err");
            return result;
        }
    }

    //[start] 查看毕业生信息

    @RequestMapping("/view")
    public String View(HttpServletRequest request, Model model) {
        try {
            String id = request.getParameter("id").trim();
            HRZZUser user = recommendService.getViewUser(id);
            model.addAttribute("user", user);
            model.addAttribute("path", request.getContextPath());

            HRZZScore score = recommendService.getScore(user.getCode(), user.getPid());

            JSONArray jsonArray = JSONArray.fromObject(score.getScore());
            Object[] objs = jsonArray.toArray();
            int i = 1;
            StringBuilder scorestr = new StringBuilder();
            for (Object object : objs) {
                if (i % 4 == 1) {
                    scorestr.append("<tr>");
                }
                JSONObject obj = JSONObject.fromObject(object);
                scorestr.append("<td>" + obj.getString("course") + "</td>");
                scorestr.append("<td>" + obj.getString("point") + "</td>");
                if (i % 4 == 0) {
                    scorestr.append("</tr>");
                }
                i++;
            }
            model.addAttribute("score", scorestr);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "Do/ZZCampus/Recommend/view";
    }

    //[end]

    //[start] 修改毕业生信息
    @RequestMapping("/edit")
    public String Edit(HttpServletRequest request, Model model) {
        try {
            String id = request.getParameter("id").trim();
            HRZZUser user = recommendService.getViewUser(id);
            model.addAttribute("user", user);
            model.addAttribute("path", request.getContextPath());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "Do/ZZCampus/Recommend/edit";
    }

    @RequestMapping(value = "/EditAction", method = RequestMethod.POST)
    public void EditAction(HttpServletRequest request, HttpServletResponse response) {
        try {
            String id = request.getParameter("id");//人员信息ID
            HRZZUser zzuser = recommendService.getUser(id);
            if (zzuser.getRstate().equals("未投简历")) {
                zzuser.setCode(request.getParameter("code"));

                utilService.editObject(zzuser);
                utilService.printJsonResult(true, "操作成功！", "no", response);
            } else {
                utilService.printJsonResult(false, "已投简历，不能修改！", "no", response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败！", "no", response);
        }
    }

    //[end]

    //[start] 部门划分

    @RequestMapping(value = "/DeptAction", method = RequestMethod.POST)
    public void DeptAction(HttpServletRequest request, HttpServletResponse response) {
        try {
            List<HRZZUser> editlist = new ArrayList<HRZZUser>();
            String zrdeptcode = request.getParameter("zrdeptcode").trim();
            String zrdeptname = request.getParameter("zrdeptname").trim();
            String[] uids = request.getParameterValues("uid");
            String pid = request.getParameter("pid").trim();
            if (uids != null) {
                ProjectInfoFlow _flow = doZZService.getflow(pid, zrdeptcode);
                String nfid = null;
                List<ProjectInfoFlow> flows = new ArrayList<ProjectInfoFlow>();
                if (_flow == null) {
                    for (EnumTools.ZZFlowState r : EnumTools.ZZFlowState.values()) {
                        if (r.ordinal() > 0) {
                            ProjectInfoFlow flow = new ProjectInfoFlow();
                            if (r.ordinal() == 1) {
                                nfid = UUID.randomUUID().toString();
                                flow.setId(nfid);
                                flow.setState(EnumTools.PlanFlowState.进行中.ordinal());
                            } else {
                                flow.setId(UUID.randomUUID().toString());
                                flow.setState(EnumTools.PlanFlowState.未开始.ordinal());
                            }

                            flow.setFid(r.ordinal());
                            flow.setNickname(r.toString());
                            flow.setPid(pid);
                            flow.setForder(r.ordinal() + 1);
                            flow.setDeptcode(zrdeptcode);
                            flow.setDeptname(zrdeptname);

                            flows.add(flow);
                        }
                    }
                } else {
                    nfid = _flow.getId();
                }

                List<HRZZUser> users = recommendService.getuserbyids(uids);
                for (HRZZUser user : users) {
                    if ((user.getState() == EnumTools.zzuserState.待审核.ordinal()
                            || user.getState() == EnumTools.zzuserState.审核中.ordinal())
                            && user.getFqstate().equals("未放弃")
                            && !user.getDeptcode().equals(zrdeptcode)) {
                        user.setDeptcode(zrdeptcode);
                        user.setDeptname(zrdeptname);
                        user.setState(EnumTools.zzuserState.审核中.ordinal());
                        user.setFid(nfid);
                        user.setPath(user.getPath() + nfid + "/");
                        editlist.add(user);
                    }
                }
                if (editlist.size() > 0) {
                    utilService.editList(editlist, flows);
                    utilService.printJsonResult(true, "操作成功！", "no", response);
                } else {
                    utilService.printJsonResult(false, "当前选中的信息不能执行此操作！", "no", response);
                }
            } else {
                utilService.printJsonResult(false, "请选择需要划分部门的毕业生！", "no", response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败！", "no", response);
        }
    }

    //[end]

    //[start] 开启关闭简历投递功能

    @RequestMapping(value = "/OpenCloseAction", method = RequestMethod.POST)
    public void OpenCloseAction(HttpServletRequest request, HttpServletResponse response) {
        try {
            String pid = request.getParameter("pid").trim();//招聘方案ID
            String fid = request.getParameter("fid").trim();//招聘流程ID
            String deptcode = request.getParameter("deptcode").trim();//责任部门编码
            ProjectInfoFlow flow = doZZService.getCurrentFlow(pid, deptcode, fid);
            if (flow.getState() == EnumTools.PlanFlowState.已完成.ordinal()) {
                flow.setState(EnumTools.PlanFlowState.进行中.ordinal());
                utilService.editObject(flow);
                utilService.printJsonResult(true, "操作成功", "no", response);
            } else if (flow.getState() == EnumTools.PlanFlowState.进行中.ordinal()) {
                flow.setState(EnumTools.PlanFlowState.已完成.ordinal());
                utilService.editObject(flow);
                utilService.printJsonResult(true, "操作成功", "no", response);
            } else {
                utilService.printJsonResult(false, "当前不能执行此操作", "no", response);
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败", "no", response);
        }
    }

    //[end]

    //[start] 流程扭转到下一步

    @SuppressWarnings({"rawtypes", "unchecked"})
    @RequestMapping(value = "/NextAction", method = RequestMethod.POST)
    public void NextAction(HttpServletRequest request, HttpServletResponse response) {
        try {
            String[] ids = request.getParameterValues("id");//人员信息ID
            if (ids != null) {
                String pid = request.getParameter("pid").trim();//招聘方案ID
                String fid = request.getParameter("fid").trim();//招聘流程ID
                String deptcode = request.getParameter("deptcode").trim();//责任部门编码
                BaseUser usr = utilService.getSessionUser(request);
                if (usr.getUdept().equals(deptcode)) {
                    List editlist = new ArrayList();
                    List<HRZZUser> users = doZZService.getUsers(pid, deptcode, ids);
                    ProjectInfoFlow nFlow = doZZService.getNextFlow(pid, deptcode, fid);
                    for (HRZZUser user : users) {
                        if (user.getFid().equals(fid) && user.getFqstate().equals("未放弃")) {
                            user.setFid(nFlow.getId());
                            user.setPath(user.getPath() + nFlow.getId() + "/");
                            editlist.add(user);
                        }
                    }

                    if (editlist.size() > 0) {
                        nFlow.setState(EnumTools.PlanFlowState.进行中.ordinal());
                        editlist.add(nFlow);

                        utilService.editList(editlist);
                        utilService.printJsonResult(true, "操作成功！", "no", response);
                    } else {
                        utilService.printJsonResult(false, "当前选中的信息不能执行此操作！", "no", response);
                    }
                } else {
                    utilService.printJsonResult(false, "您无权执行此操作！", "no", response);
                }
            } else {
                utilService.printJsonResult(false, "请选择人员信息！", "no", response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败！", "no", response);
        }
    }

    //[end]
}
